package com.julian.delegatePattern.virtualProxy;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

/**
 * It's Icon representative
 */
public class ImageProxy implements Icon {
    ImageIcon imageIcon;
    URL imageURL;
    Thread retrievalThread;
    boolean retrieving = false;

    public ImageProxy(URL imageURL) {
        this.imageURL = imageURL;
    }

    @Override
    public int getIconWidth() {
        if (imageIcon != null){
            return imageIcon.getIconWidth();
        }else {
            return 800;
        }
    }


    @Override
    public int getIconHeight() {
        if (imageIcon != null){
            return imageIcon.getIconHeight();
        }else {
            return 600;
        }
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        if (imageIcon != null){
            imageIcon.paintIcon(c,g,x,y);
        }else {
            //Draws the text given by the specified string, using this graphics context's current font and color.
            g.drawString("Loading CD cover, please wait...",x+300,y+190);
            if (!retrieving){
                retrieving = true;
                //open a subThread to load potato
                retrievalThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            imageIcon = new ImageIcon(imageURL,"CD Cover");
                            c.repaint();//repaint(0, 0, 0, width, height);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
                retrievalThread.start();
            }
        }
    }
}
